package com.spring;

import java.beans.Introspector;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * project : my-learn
 * <p> 模拟Spring容器 </p>
 *
 * @author yisl
 * @date 2022-07-22【星期五】
 **/
public class YiznApplicationContext {
    private Class appConfigClass;
    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();
    private Map<String, Object> singletonObjects = new HashMap<>();
    private List<BeanPostProcessor> beanPostProcessorList = new ArrayList<>();


    public YiznApplicationContext(Class appConfigClass) {
        this.appConfigClass = appConfigClass;
        //扫描
        scan(appConfigClass);
        //创建单列bean
        for (Map.Entry<String, BeanDefinition> stringBeanDefinitionEntry : beanDefinitionMap.entrySet()) {
            String beanName = stringBeanDefinitionEntry.getKey();
            BeanDefinition beanDefinition = stringBeanDefinitionEntry.getValue();
            if (beanDefinition.getScope().equals("singleton")) {
                Object bean = create(beanName, beanDefinition);
                singletonObjects.put(beanName, bean);
            }
        }
    }

    private Object create(String beanName, BeanDefinition beanDefinition ) {
        Class clazz = beanDefinition.getType();
        Object instance = null;
        try {
            instance = clazz.getConstructor().newInstance();
            for (Field field : clazz.getDeclaredFields()) {
                if (field.isAnnotationPresent(AutoWired.class)) {
                    field.setAccessible(true);
                    field.set(instance, getBean(field.getName()));
                }
            }
            //BeanPostProcessor
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessBeforeInitialization(instance, beanName);
            }
            if (instance instanceof InitializingBean) {
                ((InitializingBean) instance).afterPropertiesSet();
            }
            //BeanPostProcessor
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorList) {
                instance = beanPostProcessor.postProcessAfterInitialization(instance, beanName);
            }


        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return instance;
    }

    private void scan(Class appConfigClass) {
        if (appConfigClass.isAnnotationPresent(ComponentScan.class)) {
            ComponentScan annotation = (ComponentScan) appConfigClass.getAnnotation(ComponentScan.class);
            String path = annotation.value();
            ClassLoader classLoader = annotation.getClass().getClassLoader();
            URL url = classLoader.getResource(path.replace(".", "/"));
            File file = new File(url.getFile());
            if(file.isDirectory()){
                File[] files = file.listFiles();
                for (File file1 : files) {
                    try {
                        String absolutePath = file1.getAbsolutePath();
                        Class<?> aClass = classLoader.loadClass(absolutePath.substring(absolutePath.indexOf("com"), absolutePath.indexOf(".class")).replace("/", "."));
                        if (aClass.isAnnotationPresent(Component.class)){

                            if (BeanPostProcessor.class.isAssignableFrom(aClass)) {
                                BeanPostProcessor o = (BeanPostProcessor) aClass.getConstructor().newInstance();
                                beanPostProcessorList.add(o);
                            }
                            
                            Component component = aClass.getAnnotation(Component.class);
                            String beanName = component.value();
                            if ("".equals(beanName)) {
                                beanName= Introspector.decapitalize(aClass.getSimpleName());
                            }

                            BeanDefinition beanDefinition = new BeanDefinition();
                            beanDefinition.setType(aClass);

                            if (aClass.isAnnotationPresent(Scope.class)){
                                //判断是否是单列
                                Scope scopAnnotation = aClass.getAnnotation(Scope.class);
                                String value = scopAnnotation.value();
                                beanDefinition.setScope(value);

                            }else {
                                //单列
                                beanDefinition.setScope("singleton");
                            }
                            beanDefinitionMap.put(beanName, beanDefinition);
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public Object getBean(String userService) {
        if (!beanDefinitionMap.containsKey(userService)) {
            throw new NullPointerException();
        }
        BeanDefinition beanDefinition = beanDefinitionMap.get("userService");
        if (beanDefinition.getScope().equals("singleton")) {
            Object singletonBean = singletonObjects.get(userService);
            if (singletonBean==null){
                singletonBean = create(userService, beanDefinition);
                singletonObjects.put(userService, beanDefinition);
            }
            return singletonBean;
        }else{
            //原型
            Object bean = create(userService,beanDefinition );
            return bean;
        }
    }
}
